package com.st.warehouse.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 基础地址
 */
public class RetrofitUtil {

    //public static String HOST_URL = "http://192.168.31.46:1221/app/test/";  // 测试
    public static String HOST_URL = "http://124.221.243.113:1221/app/";  // 正式
//    public static String HOST_URL = "http://192.168.1.9:1221/app/";  // 本地


    public static <T> T build(Class<?> serviceClass){
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(HOST_URL)
                .addConverterFactory(GsonConverterFactory.create())//Gson解析器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//设置支持RXjava2
                .build();
        return (T) retrofit.create(serviceClass);
    }

    /**
     * 获取接口返回数据
     */
    public static JSONObject getDataFromResponse(Response<ResponseBody> response) throws IOException {
        if (response != null && response.isSuccessful() && response.body() != null) {
            String responseStr = response.body().string();
            if (StringUtils.isJson(responseStr)) {
                return JSONObject.parseObject(responseStr);
            } else {
                return getErrorJson("网络异常，数据异常");
            }
        } else {
            return getErrorJson("网络异常，连接超时");
        }
    }
    /**
     * 获取报错的信息
     */
    private static JSONObject getErrorJson(String msg) {
        JSONObject data = new JSONObject();
        data.put("code", 500);
        data.put("success", false);
        data.put("msg", msg);
        return data;
    }
}
